import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutterdemo/common/constants.dart';
import 'package:flutterdemo/generated/json/base/json_convert_content.dart';
import 'package:flutterdemo/http/http.dart';
import 'package:flutterdemo/library/sqflite/compare_provider.dart';
import 'package:flutterdemo/library/sqflite/face_provider.dart';
import 'package:flutterdemo/library/sqflite/face_quality_provider.dart';
import 'package:flutterdemo/models/entity/compare_entity.dart';
import 'package:flutterdemo/models/entity/face_detect_entity.dart';
import 'package:flutterdemo/models/entity/face_entity.dart';
import 'package:flutterdemo/models/entity/face_info_entity.dart';
import 'package:flutterdemo/utils/file_util.dart';
import 'package:flutterdemo/utils/img_util.dart';
import 'package:flutterdemo/utils/sp_util.dart';
import 'package:flutterdemo/utils/toast_util.dart';
import 'package:path_provider/path_provider.dart';

class FaceComparePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _FaceComparePageState();
  }
}

class _FaceComparePageState extends State<FaceComparePage> {
  int _compareCount = 0; //对比个数
  int _pageIndex = 1;
  int _totalLocal = 0;
  int _totalServer = 0;
  String _deviceNo = '17L西门';
  String _style = 'm2000';
  String _communityName = 'xxxxx';
  String _imageServer = "http://xxxxxxxxx/";

  @override
  void initState() {
    super.initState();
    FaceQualityProvider().querySizeByCommunity(_communityName).then((value) {
      setState(() {
        _totalLocal = value;
        _compareCount = value;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('人脸对比'),
      ),
      body: _body(),
    );
  }

  Widget _body() {
    return Column(
      children: <Widget>[
        Text('$_communityName,个数=$_compareCount/$_totalServer'),
        Container(
          padding: EdgeInsets.all(5),
          child: OutlineButton(
            child: Text("通行记录,人脸比对"),
            onPressed: () {
              _compare();
            },
          ),
        ),
        Container(
          padding: EdgeInsets.all(5),
          child: OutlineButton(
            child: Text("下载人脸,测算图片大小"),
            onPressed: () {
              _downloadFace();
            },
          ),
        ),
        Container(
          padding: EdgeInsets.all(5),
          child: OutlineButton(
            child: Text("下载人脸,质量检测"),
            onPressed: () {
              // FaceQualityProvider().deleteByCommunityName(_communityName);
              _downloadFaceToDetect();
            },
          ),
        ),
        Container(
          padding: EdgeInsets.all(5),
          child: OutlineButton(
            child: Text("同小区不同设备,通行记录合并"),
            onPressed: () {
              FaceModelProvider().merge();
            },
          ),
        ),
        Container(
          padding: EdgeInsets.all(5),
          child: OutlineButton(
            child: Text("质量检测与识别均值数据对比,并合并"),
            onPressed: () {
              _scoreAvg();
            },
          ),
        ),
        Container(
          padding: EdgeInsets.all(5),
          child: OutlineButton(
            child: Text("通行记录分值各区间分布"),
            onPressed: () {
              FaceModelProvider().queryDistribution();
            },
          ),
        ),
        Container(
          padding: EdgeInsets.all(5),
          child: OutlineButton(
            child: Text("下载本地路径图片"),
            onPressed: () {
              _downloadLocalFace();
            },
          ),
        ),
      ],
    );
  }

  ///计算平均值，并与质量检测表合并
  _scoreAvg() async {
    List<FaceModel> facdeModels = await FaceModelProvider().queryAvg();
    print("数据size=${facdeModels.length}");
    List<FaceQuality> faceQualityList = await FaceQualityProvider().queryAll();
    facdeModels.forEach((model) {
      faceQualityList.forEach((quality) {
        if (model.staffName == quality.staffName &&
            quality.communityName == _communityName) {
          quality.scoreAvg = model.score;
          print(' quality=${quality.toMap()}');
          FaceQualityProvider().update(quality);
        }
      });
    });
  }

  _downloadFace() async {
    //Android/data/com.jzqf.flutterdemo/files
    String localDirectory = (await getExternalStorageDirectory()).path;
    HttpManager().tokenKey = "Authorization";
    SpUtil().putString(Constants.token, "xxxxxxxxxxxxxx");
    HttpManager().post("xxxxxxxx", {
      "Pagination": {
        "PageIndex": _pageIndex,
        "PageRows": 5,
        "SortField": "Dateandtime",
        "SortType": "desc"
      }
    }, (data) {
      FaceInfoEntity faceInfoEntity =
          JsonConvert.fromJsonAsT<FaceInfoEntity>(data);
      faceInfoEntity.data.records.forEach((face) async {
        String faceUrl =
            "$_imageServer${face.faceUrl}?x-oss-process=style/$_style";
        String facePath =
            '$localDirectory/${_imageName(face.faceUrl)}'; //抠图本地路径
        await HttpManager().downloadFile(faceUrl, facePath);
      });
      _totalLocal += 5;
      _totalServer = faceInfoEntity.data.recordCount;
      if (_totalLocal < _totalServer) {
        _pageIndex++;
        Future.delayed(Duration(milliseconds: 2000), () {
          _downloadFace();
        });
      } else {
        print('下载图片完成');
      }
      setState(() {
        _compareCount++;
      });
    }, (error) {
      ToastUtil.showToastCenter(error);
      setState(() {
        _compareCount++;
      });
    });
  }

  _downloadFaceToDetect() async {
    //Android/data/com.jzqf.flutterdemo/files
    String localDirectory = (await getExternalStorageDirectory()).path;
    HttpManager().tokenKey = "Authorization";
    SpUtil().putString(
        Constants.token, "xxxxxxxxxxxxxx");
    HttpManager().post("xxxxxxxxxx", {
      "Pagination": {
        "PageIndex": _pageIndex,
        "PageRows": 5,
        "SortField": "Dateandtime",
        "SortType": "desc"
      }
    }, (data) {
      FaceInfoEntity faceInfoEntity =
          JsonConvert.fromJsonAsT<FaceInfoEntity>(data);
      faceInfoEntity.data.records.forEach((face) async {
        String faceUrl =
            "$_imageServer${face.faceUrl}?x-oss-process=style/$_style";
        String facePath =
            '$localDirectory/${_imageName(face.faceUrl)}'; //抠图本地路径
        await HttpManager().downloadFile(faceUrl, facePath);
        ImageUtil.imageSize(facePath,
            ImageStreamListener((ImageInfo imageInfo, bool _) async {
          String faceBase64 = await ImageUtil.image2Base64(facePath);
          _detect(face, faceUrl, facePath, imageInfo.image.width,
              imageInfo.image.height, faceBase64);
        }));
      });
      _totalLocal += 5;
      _totalServer = faceInfoEntity.data.recordCount;
      if (_totalLocal < _totalServer) {
        _pageIndex++;
        Future.delayed(Duration(milliseconds: 5000), () {
          _downloadFaceToDetect();
        });
      } else {
        print('下载图片完成');
      }
    }, (error) {
      ToastUtil.showToastCenter(error);
    });
  }

  _detect(FaceInfoDataRecord faceInfoDataRecord, String faceUrl,
      String facePath, int imageWidth, int imageHeight, String faceBase64) {
    HttpManager().post(
        'https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=24.560d1e269af7c48873d8256095b8aed2.2592000.1613635377.282335-20380462',
        {
          "image": faceBase64,
          "image_type": "BASE64",
          'face_field':
              "expression,glasses,quality,eye_status,emotion,face_type,gender",
          "face_type": "LIVE",
          "liveness_control": "NONE"
        }, (data) async {
      FaceDetectEntity faceDetectEntity =
          JsonConvert.fromJsonAsT<FaceDetectEntity>(data);
      FaceDetectResultFaceList faceDetect = faceDetectEntity.result.faceList[0];
      FaceQuality faceQuality = FaceQuality();
      faceQuality.communityName = _communityName;
      faceQuality.faceUrl = faceUrl;
      faceQuality.imgWidth = imageWidth;
      faceQuality.imgHeight = imageHeight;
      faceQuality.imgLength = File(facePath).lengthSync() / 1000;
      if (faceDetect.quality.blur > 0.5) {
        faceQuality.reason = 'blur>0.5';
        faceQuality.quality = '差';
      } else if (faceDetect.quality.illumination < 80) {
        faceQuality.reason = 'illumination < 80';
        faceQuality.quality = '差';
      } else if (faceDetect.quality.illumination > 200) {
        faceQuality.reason = 'illumination > 200';
        faceQuality.quality = '差';
      } else if (faceDetect.quality.occlusion.leftEye > 0.3) {
        faceQuality.reason = 'leftEye > 0.3';
        faceQuality.quality = '差';
      } else if (faceDetect.quality.occlusion.rightEye > 0.3) {
        faceQuality.reason = 'rightEye > 0.3';
        faceQuality.quality = '差';
      } else if (faceDetect.quality.occlusion.nose > 0.5) {
        faceQuality.reason = 'nose > 0.5';
        faceQuality.quality = '差';
      } else if (faceDetect.quality.occlusion.mouth > 0.5) {
        faceQuality.reason = 'mouth > 0.5';
        faceQuality.quality = '差';
      } else if (faceDetect.quality.occlusion.leftCheek > 0.5) {
        faceQuality.reason = 'leftCheek > 0.5';
        faceQuality.quality = '差';
      } else if (faceDetect.quality.occlusion.rightCheek > 0.5) {
        faceQuality.reason = 'rightCheek > 0.5';
        faceQuality.quality = '差';
      } else if (faceDetect.angle.pitch.abs() > 20) {
        faceQuality.reason = 'pitch.abs() > 20';
        faceQuality.quality = '差';
      } else if (faceDetect.angle.roll.abs() > 20) {
        faceQuality.reason = 'roll.abs() > 20';
        faceQuality.quality = '差';
      } else if (faceDetect.angle.yaw.abs() > 20) {
        faceQuality.reason = 'yaw.abs() > 20';
        faceQuality.quality = '差';
      } else {
        faceQuality.quality = '优秀';
      }
      faceQuality.staffName = faceInfoDataRecord.faceName;
      faceQuality.staffNo = "$_communityName-${faceInfoDataRecord.id}";
      faceQuality.uploadTime = faceInfoDataRecord.dateandtime;
      faceQuality.glasses = faceDetect.glasses.type;
      faceQuality.faceScale = faceDetect.location.width / imageWidth;
      faceQuality.faceSize = faceDetect.location.width;
      faceQuality.gender = faceDetect.gender.type;
      FaceQualityProvider().insert(faceQuality);
      FileUtil.deleteFile(facePath);
      setState(() {
        _compareCount++;
      });
    }, (error) {
      ToastUtil.showToastCenter(error);
      setState(() {
        _compareCount++;
      });
    });
  }

  _compare() {
    HttpManager().tokenKey = "Authorization";
    SpUtil().putString(
        Constants.token, "xxxxxxxxxxxx");
    HttpManager().post("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", {
      "QueryParam": {
        "CompanyId": 65,
        "AreaId": 21954,
        "OrgId": 21955,
        "WyCommunityId": 7971,
        "Account": "18538710174",
        "AccessId": 185,
        "ChannelId": "",
        "IdentityType": "",
        "PasswayType": "",
        "AccessTypeId": "",
        "StartTime": "2020-12-27 00:00:00",
        "EndTime": "2021-01-04 23:59:59",
        "KeyWords": ""
      },
      "Pagination": {"PageIndex": _pageIndex, "PageRows": 5}
    }, (data) {
      FaceEntity faceEntity = JsonConvert.fromJsonAsT<FaceEntity>(data);
      //下载图片
      faceEntity.data.records.forEach((element) async {
        _downloadImage(element);
      });
      _totalLocal += 5;
      _totalServer = faceEntity.data.recordCount;
      if (_totalLocal < _totalServer) {
        _pageIndex++;
        Future.delayed(Duration(milliseconds: 1000), () {
          _compare();
        });
      } else {
        print('当前数据已对比完成');
      }
      return faceEntity;
    }, (error) {
      ToastUtil.showToastCenter(error);
      return null;
    });
  }

  /// 下载图片
  Future _downloadImage(FaceDataRecord faceDataRecord) async {
    String faceUrl =
        "$_imageServer${faceDataRecord.facePicture}?x-oss-process=style/$_style";
    String cropUrl =
        "$_imageServer${faceDataRecord.openPicture}?x-oss-process=style/$_style";
    String localDirectory = (await getExternalStorageDirectory()).path;
    String facePath =
        localDirectory + "/" + _imageName(faceDataRecord.facePicture); //抠图本地路径
    String cropPath =
        localDirectory + "/" + _imageName(faceDataRecord.openPicture); //原图片本地路径
    await HttpManager().downloadFile(faceUrl, facePath);
    await HttpManager().downloadFile(cropUrl, cropPath);
    String faceBase64 = await ImageUtil.image2Base64Compress(facePath);
    String cropBase64 = await ImageUtil.image2Base64Compress(cropPath);
    //上传图片对比
    HttpManager().post(
        'https://aip.baidubce.com/rest/2.0/face/v3/match?access_token=24.560d1e269af7c48873d8256095b8aed2.2592000.1613635377.282335-20380462',
        [
          {
            "image": faceBase64,
            "image_type": "BASE64",
            "face_type": "LIVE",
            "quality_control": "LOW",
            "liveness_control": "NONE"
          },
          {
            "image": cropBase64,
            "image_type": "BASE64",
            "face_type": "LIVE",
            "quality_control": "LOW",
            "liveness_control": "NONE"
          }
        ], (data) {
      //插入数据库
      var compare = new Compare();
      compare.deviceNo = _deviceNo;
      compare.staff_name = faceDataRecord.staffName;
      compare.faceUrl = faceUrl;
      compare.cropUrl = cropUrl;
      compare.compareTime = faceDataRecord.openDate;
      compare.style = _style;
      compare.size = File(facePath).lengthSync();
      //拿到百度对比结果
      CompareEntity compareEntity =
          JsonConvert.fromJsonAsT<CompareEntity>(data);
      compare.errorCode = compareEntity.errorCode;
      if (compareEntity.errorCode == 0) {
        print('识别结果:${compareEntity.result.score} $cropUrl');
        compare.score = compareEntity.result.score;
      } else {
        print(
            '${DateTime.now()} 识别失败,${compareEntity.errorMsg} $faceUrl \n $cropUrl ');
      }
      CompareProvider().insert(compare);
      FileUtil.deleteFile(cropPath);
      setState(() {
        _compareCount++;
      });
    }, (error) {
      ToastUtil.showToastCenter(error);
      setState(() {
        _compareCount++;
      });
    });
  }

  /// 下载本地图片
  _downloadLocalFace() async {
    Directory directory = (await getExternalStorageDirectory());
    String localDirectory = directory.path;
    String imageUrl = '/face/2019-12/8/1575770536663.jpg,/face/2020-6/24/1592988666757.jpg,/face/2020-7/2/1593696578948.jpg,/face/2020-7/2/1593696730569.jpg,/face/2020-7/3/1593760010206.jpg,/face/2021-2/27/1614399379380.jpg,/face/2020-7/4/1593856620236.jpg,/face/2020-7/5/1593928734280.jpg,/face/2020-7/6/1593998574850.jpg,/face/2020-7/6/1594031861534.jpg,/face/2020-7/10/1594384370591.jpg,/face/2020-7/11/1594433562890.jpg,/face/2020-7/11/1594460567216.jpg,/face/2020-7/11/1594464084666.jpg,/face/2020-7/12/1594525427667.jpg,/face/2020-7/12/1594537011456.jpg,/face/2020-7/12/1594537044745.jpg,/face/2021-2/7/1612673729571.jpg,/face/2020-7/12/1594539725484.jpg,/face/2020-7/13/1594599036238.jpg,/face/2020-7/14/1594686382391.jpg,/face/2020-7/14/1594699781458.jpg,/face/2020-7/14/1594715251886.jpg,/face/2020-7/14/1594729546793.jpg,/face/2020-7/16/1594888485664.jpg,/face/2020-7/17/1594950192290.jpg,/face/2020-7/17/1594950232974.jpg,/face/2020-7/17/1594983153209.jpg,/face/2020-7/18/1595065753195.jpg,/face/2020-7/18/1595069306714.jpg,/face/2020-7/19/1595130364336.jpg,/face/2020-7/19/1595140848137.jpg,/face/2020-7/19/1595140895676.jpg,/face/2020-7/19/1595147037480.jpg,/face/2020-7/19/1595160553415.jpg,/face/2020-7/19/1595146295574.jpg,/face/2020-7/19/1595151249243.jpg,/face/2020-7/19/1595157064478.jpg,/face/2020-7/20/1595207874736.jpg,/face/2020-7/20/1595234020113.jpg,/face/2020-7/20/1595235299628.jpg,/face/2020-7/20/1595237301682.jpg,/face/2020-7/20/1595247750325.jpg,/face/2020-7/23/1595471854356.jpg,/face/2020-7/23/1595472189429.jpg,/face/2020-7/23/1595489194542.jpg,/face/2020-7/23/1595497022166.jpg,/face/2020-7/23/1595503706177.jpg,';
    List<String> imageUrls = imageUrl.split(',');
    imageUrls.forEach((url) async {
      String faceUrl = "$_imageServer$url";
      String facePath = '$localDirectory/${_imageName(url)}'; //抠图本地路径
      await HttpManager().downloadFile(faceUrl, facePath);
    });
  }

  ///获取图片名称  包含后缀
  String _imageName(String imageUrl) {
    return imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
  }
}
